package com.hongqianping.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hongqianping.entity.BuserTable;
import com.hongqianping.entity.CartTable;
import com.hongqianping.entity.GoodsTable;
import com.hongqianping.entity.GoodsType;
import com.hongqianping.service.CartTableService;
import com.hongqianping.service.GoodsTableService;
import com.hongqianping.service.GoodsTypeService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class CartController {

    @Autowired
    private CartTableService cartTableService;

    @Autowired
    private GoodsTableService goodsTableService;

    @Autowired
    private GoodsTypeService goodsTypeService;

    @GetMapping("/cart")
    public String viewCart(HttpSession session, Model model) {
        BuserTable currentUser = (BuserTable) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login.html"; // 如果未登录，重定向到登录页面
        }

        // 获取导航栏所有商品类型
        List<GoodsType> goodsTypes = goodsTypeService.list();
        model.addAttribute("goodsTypes", goodsTypes);

        LambdaQueryWrapper<CartTable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CartTable::getBusertableId, currentUser.getId())
                    .orderByAsc(CartTable::getId); // 按购物车项ID排序
        List<CartTable> cartItems = cartTableService.list(queryWrapper);

        List<Map<String, Object>> cartDisplayList = new ArrayList<>();
        double totalAmount = 0.0;

        for (CartTable item : cartItems) {
            GoodsTable goods = goodsTableService.getById(item.getGoodstableId());
            if (goods != null) {
                Map<String, Object> cartEntry = new HashMap<>();
                cartEntry.put("cartItemId", item.getId()); // 这是正确的CartTable ID
                cartEntry.put("goods", goods);
                cartEntry.put("shoppingNum", item.getShoppingnum());
                cartEntry.put("subtotal", goods.getGrprice() * item.getShoppingnum()); // 预先计算小计，方便使用

                cartDisplayList.add(cartEntry);
                totalAmount += goods.getGrprice() * item.getShoppingnum();
            }
        }

        model.addAttribute("cartDetails", cartDisplayList);
        model.addAttribute("totalAmount", totalAmount);
        return "cart"; // 解析到 src/main/resources/templates/user/cart.html
    }

    @PostMapping("/addToCart")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> addToCart(@RequestParam("goodsId") Integer goodsId,
                                                      @RequestParam("quantity") Integer quantity,
                                                      HttpSession session) {
        BuserTable currentUser = (BuserTable) session.getAttribute("currentUser");
        Map<String, Object> response = new HashMap<>();

        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "请先登录！");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }

        // 检查商品是否已存在于当前用户的购物车中
        LambdaQueryWrapper<CartTable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CartTable::getBusertableId, currentUser.getId())
                    .eq(CartTable::getGoodstableId, goodsId);
        CartTable existingCartItem = cartTableService.getOne(queryWrapper);

        if (existingCartItem != null) {
            // 如果商品已存在，更新数量
            existingCartItem.setShoppingnum(existingCartItem.getShoppingnum() + quantity);
            boolean updated = cartTableService.updateById(existingCartItem);
            if (updated) {
                response.put("success", true);
                response.put("message", "购物车商品数量已更新！");
                return new ResponseEntity<>(response, HttpStatus.OK);
            } else {
                response.put("success", false);
                response.put("message", "更新购物车失败，请稍后再试！");
                return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } else {
            // 添加新商品到购物车
            CartTable newCartItem = new CartTable();
            newCartItem.setBusertableId(currentUser.getId());
            newCartItem.setGoodstableId(goodsId);
            newCartItem.setShoppingnum(quantity);
            boolean saved = cartTableService.save(newCartItem);
            if (saved) {
                response.put("success", true);
                response.put("message", "商品已成功加入购物车！");
                return new ResponseEntity<>(response, HttpStatus.OK);
            } else {
                response.put("success", false);
                response.put("message", "加入购物车失败，请稍后再试！");
                return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
    }

    @PostMapping("/updateCart")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updateCart(@RequestParam("cartItemId") Integer cartItemId,
                                                      @RequestParam("quantity") Integer quantity,
                                                      HttpSession session) {
        BuserTable currentUser = (BuserTable) session.getAttribute("currentUser");
        Map<String, Object> response = new HashMap<>();

        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "请先登录！");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }

        CartTable cartItem = cartTableService.getById(cartItemId);
        if (cartItem != null && cartItem.getBusertableId().equals(currentUser.getId())) {
            if (quantity <= 0) {
                // 如果数量为0或更少，则移除商品
                cartTableService.removeById(cartItemId);
                response.put("message", "商品已从购物车移除。");
            } else {
                // 更新数量
                cartItem.setShoppingnum(quantity);
                cartTableService.updateById(cartItem);
                response.put("message", "购物车商品数量已更新！");
            }

            // 更新/移除后重新计算总金额
            LambdaQueryWrapper<CartTable> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CartTable::getBusertableId, currentUser.getId());
            List<CartTable> updatedCartItems = cartTableService.list(queryWrapper);
            double newTotalAmount = 0.0;
            for (CartTable item : updatedCartItems) {
                GoodsTable goods = goodsTableService.getById(item.getGoodstableId());
                if (goods != null) {
                    newTotalAmount += goods.getGrprice() * item.getShoppingnum();
                }
            }
            response.put("success", true);
            response.put("totalAmount", newTotalAmount);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } else {
            response.put("success", false);
            response.put("message", "购物车商品不存在或无权操作！");
            return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
        }
    }

    @PostMapping("/removeCartItem")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> removeCartItem(@RequestParam("cartItemId") Integer cartItemId,
                                                             HttpSession session) {
        BuserTable currentUser = (BuserTable) session.getAttribute("currentUser");
        Map<String, Object> response = new HashMap<>();

        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "请先登录！");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }

        CartTable cartItem = cartTableService.getById(cartItemId);
        if (cartItem != null && cartItem.getBusertableId().equals(currentUser.getId())) {
            cartTableService.removeById(cartItemId);
            response.put("message", "商品已成功移除购物车！");

            // 移除后重新计算总金额
            LambdaQueryWrapper<CartTable> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CartTable::getBusertableId, currentUser.getId());
            List<CartTable> updatedCartItems = cartTableService.list(queryWrapper);
            double newTotalAmount = 0.0;
            for (CartTable item : updatedCartItems) {
                GoodsTable goods = goodsTableService.getById(item.getGoodstableId());
                if (goods != null) {
                    newTotalAmount += goods.getGrprice() * item.getShoppingnum();
                }
            }
            response.put("success", true);
            response.put("totalAmount", newTotalAmount);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } else {
            response.put("success", false);
            response.put("message", "购物车商品不存在或无权操作！");
            return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
        }
    }

    @PostMapping("/clearCart")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> clearCart(HttpSession session) {
        BuserTable currentUser = (BuserTable) session.getAttribute("currentUser");
        Map<String, Object> response = new HashMap<>();

        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "请先登录！");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }

        LambdaQueryWrapper<CartTable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CartTable::getBusertableId, currentUser.getId());
        boolean removed = cartTableService.remove(queryWrapper);

        if (removed) {
            response.put("success", true);
            response.put("message", "购物车已清空！");
            response.put("totalAmount", 0.0); // 清空后总金额为0
            return new ResponseEntity<>(response, HttpStatus.OK);
        } else {
            response.put("success", false);
            response.put("message", "清空购物车失败或购物车已为空！");
            response.put("totalAmount", 0.0); // 即使购物车已为空或移除失败，总金额也为0
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
} 